package com.inxedu.os.edu.controller.course;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.inxedu.os.edu.pojo.*;
import com.inxedu.os.edu.service.course.CourseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/*
* 课程管理下的课程管理
*
* */
@Controller
@RequestMapping("admin")
@Api(value = "课程管理", tags = "课程管理")
public class CourseManangeController {
    public static Gson gson = (new GsonBuilder()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    private static final Logger logger = LoggerFactory.getLogger(CourseManangeController.class);
     @InitBinder({"queryCourse"})
    public void initBinderSysFunction(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("queryCourse.");
}
    @Autowired
    private CourseService courseService;
    /*@RequestMapping("/admin/cou/list")
    public String selectCourseList(Model model ,@RequestParam(defaultValue = "1") int page){
        //查询专业

        QuerySubject querySubject=new QuerySubject();
        List<Map<String,Object>> subject = courseService.selectSybject(querySubject);


        PageHelper.startPage(page,10);
        List<Map<String, Object>> maps = courseService.selectCourseList();
        model.addAttribute("courseList",maps);



       // ModelAndView moderls=new ModelAndView();
        PageInfo<List<Map<String, Object>>> info = new PageInfo(maps);
        model.addAttribute("page",info);
        model.addAttribute("subjectList",gson.toJson(subject));

        return "/view/inxedu/admin/course/course_list";
    }*/
//删除功能
    @RequestMapping(value="/cou/avaliable/{course.courseId}",method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParam(name = "courseId", value = "课程的Id", required = true, dataType = "courseId")
    @ApiOperation(value = "删除课程", notes = "删除课程")
    public String deleteCourseList(@PathVariable("course.courseId") Long courseId) {


        int i = courseService.deleteCourseList(courseId);
        result result=new result();
        if(i>0){
            result.setSuccess(true);
            result.setMessage("删除成功");
        }else{
            result.setMessage("删除失败");
            result.setSuccess(false);
        }
        String json = gson.toJson(result);


        return json;

    }

    //模糊查询
    @RequestMapping(value="/cou/list",method = {RequestMethod.GET,RequestMethod.POST})
    @ApiImplicitParam(name = "EduCourserNew", value = "新建的课程对象", required = true, dataType = "EduCourserNew")
    @ApiOperation(value = "课程的模糊查询", notes = "课程的模糊查询")
    public String showCourselist(Model model, @ModelAttribute("queryCourse") EduCourserNew queryCourse, @RequestParam(defaultValue = "1")int page){


        QuerySubject querySubject=new QuerySubject();
        List<Map<String,Object>> subject = courseService.selectSybject(querySubject);
        //查询专业
        PageHelper.startPage(page,10);
        List<Map<String, Object>> maps = courseService.selectByName(queryCourse);
        System.out.println(maps);
        PageInfo<Map<String, Object>> info = new PageInfo(maps);
        System.out.println("----------------------------"+info.getTotal()+"pageSize"+info.getPageSize()+"pageNum"+info.getPageNum());
        model.addAttribute("subjectList",gson.toJson(subject));
        model.addAttribute("page",info);
        model.addAttribute("courseList",maps);
        return "/view/inxedu/admin/course/course_list";


    }




//修改课程
    @RequestMapping(value="/cou/initUpdate/{courseId}",method = RequestMethod.GET)
    @ApiImplicitParam(name = "courseId", value = "课程Id", required = true, dataType = "courseId")
    @ApiOperation(value = "修改课程（查询操作）", notes = "修改课程（查询操作）")
    public String updateCourseList(@PathVariable(value="courseId") Long courseId, Model model,HttpServletRequest request){
        Map<String, Object> eduCourse = courseService.queryCourseById(courseId);
        //查询专业
        QuerySubject querySubject=new QuerySubject();
        List<Map<String,Object>> subject = courseService.selectSybject(querySubject);
        model.addAttribute("subjectList",gson.toJson(subject));
        model.addAttribute("course",eduCourse);


        return "view/inxedu/admin/course/update_course";
    }
    /**
    * 修改课程
    *
    * */
    @RequestMapping(value="/cou/updateCourse",method = RequestMethod.POST)
    @ApiImplicitParam(name = "EduCourse", value = "课程对象", required = true, dataType = "EduCourse")
    @ApiOperation(value = "修改课程（修改操作）", notes = "修改课程（修改操作）")
    public ModelAndView goUpdateCourse(HttpServletRequest request, EduCourse eduCourse){
        System.out.println(eduCourse.getCourseId());

        ModelAndView model = new ModelAndView();
        try{
            model.setViewName("redirect:/admin/cou/list");
            eduCourse.setCourseId((Long) eduCourse.getCourseId());
            System.out.println(eduCourse.getCourseId());
            eduCourse.setUpdateTime(new Date());

            courseService.goUpdateCourse(eduCourse);
            //获得历史请求 跳转
            Object uri = request.getSession().getAttribute("courseListUri");
            if(uri!=null){
                model.setViewName("redirect:"+uri.toString());
            }
        }catch (Exception e){


        }
        //修改课程与讲师的关联数
        this.addCourseTeacher(request,eduCourse);
        return model;



    }

    //创建课程
    @RequestMapping(value="/cou/toAddCourse",method = RequestMethod.GET)
   // @ApiImplicitParam(name = "EduCourse", value = "课程对象", required = true, dataType = "EduCourse")
    @ApiOperation(value = "查询专业", notes = "查询专业")
    public String createCourse(Model model){
    //查询专业
    QuerySubject querySubject=new QuerySubject();
        List<Map<String,Object>> subject = courseService.selectSybject(querySubject);
        model.addAttribute("subjectList",gson.toJson(subject));

        return "view/inxedu/admin/course/add_course";


    }

    @RequestMapping(value = "/cou/addCourse",method = RequestMethod.POST)
    @ApiImplicitParam(name = "EduCourse", value = "课程对象", required = true, dataType = "EduCourse")
    @ApiOperation(value = "创建课程", notes = "创建课程")
    public String add(EduCourse eduCourse, HttpServletRequest request){
        eduCourse.setAddTime(new Date());
        eduCourse.setUpdateTime(new Date());
        courseService.createCourse(eduCourse);
        //添加课程与讲师相关的数据
        this.addCourseTeacher(request,eduCourse);

    return "redirect:/admin/cou/list";
    }
    //讲师查询
    @RequestMapping(value = "/teacher/selectlist/{type}",method = RequestMethod.GET)
    @ApiImplicitParam(name = "QueryTeacher", value = "讲师查询（辅助类）", required = true, dataType = "QueryTeacher")
    @ApiOperation(value = "创建课程", notes = "创建课程")
    public  String selectTeacher(Model model,HttpServletRequest request,@ModelAttribute("queryTeacher")QueryTeacher queryTeacher,@PathVariable("type")String type){
        //查询讲师
        List<EduTeacher> teacherList=  courseService.queryTeacherList();
        model.addAttribute("teacherList",teacherList);
        queryTeacher.getIsStar();
        model.addAttribute("queryTeacher",queryTeacher);
        model.addAttribute("type",type);


        return "view/inxedu/admin/teacher/select_teacher_list";
    }

    /**
     * 添加课程与讲师的关联数据
     * @param request
     * @param eduCourse 课程
     */

    private void addCourseTeacher(HttpServletRequest request, EduCourse eduCourse){
        //先清除之前的数据 再添加
        courseService.deleteCourseTeacher(eduCourse.getCourseId());
        String teacherIds = request.getParameter("teacherIdArr");
        if(teacherIds!=null&& teacherIds.trim().length()>0){
            String[]tcIdArr=teacherIds.split(",");
            StringBuffer val=new StringBuffer();
            for(int i=0;i<tcIdArr.length;i++){
                if(i<tcIdArr.length-1){
                    val.append("("+eduCourse.getCourseId()+","+tcIdArr[i]+"),");
                }else{
                    val.append("("+eduCourse.getCourseId()+","+tcIdArr[i]+")");
                }
            }
            courseService.addCouseTeacher(val.toString());
        }
    }





}
